using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Crossborder.Common.EventBusHelper;
using Crossborder.Common.RedisModule;
using Crossborder.Core.Const;
using Crossborder.Core.Cto;
using Crossborder.Core.Dto;
using Crossborder.IService;
using Microsoft.Identity.Client;
using Newtonsoft.Json;

namespace Crossborder.Service.ShoppingCart
{
    public class ShoppingCartService : IShoppingCartService
    {
        public RedisWorker _Redis { get; set; }

        public IMapper _Mapper { get; set; }

        public LocalEventBus<ShoppingCartInputDto> _BusShoppingCartDto { get; set; }
        public ShoppingCartService(RedisWorker redis, IMapper mapper, LocalEventBus<ShoppingCartInputDto> busShoppingCartDto)
        {
            _Redis = redis;
            _Mapper = mapper;
            _BusShoppingCartDto = busShoppingCartDto;
        }

        public async Task<List<ShoppingCartDto>> GetShoppingCart(string userId)
        {
            List<ShoppingCartDto> result = new();
            var keys = await _Redis.GetRedisZSetAsync($"{RedisKeyName.IDX}:{RedisKeyName.USER_KEY}:{userId}");
            foreach (var key in keys)
            {
                var data = await _Redis.GetHashMemoryAsync<ShoppingCartCto>(key);
                var map = _Mapper.Map<ShoppingCartDto>(data);
                result.Add(map);
            }
            return result;

        }

        public async Task SetShoppingCart(string userId, ShoppingCartInputDto inputDto)
        {

            var idxKey = $"{RedisKeyName.IDX}:{RedisKeyName.USER_KEY}:{userId}";
            var key = $"{RedisKeyName.CART}:{RedisKeyName.USER_KEY}:{userId}:{RedisKeyName.PRODUCT_KEY}:{inputDto.ProductId}";
            var data = await _Redis.GetHashMemoryAsync<ShoppingCartCto>(key);
            if (!string.IsNullOrWhiteSpace(data.ProductId))
            {
                data.ProductNum++;
                #region 临时处理
                data.Photos = "";
                // Todo: 写入时获取产品图片和版本信息
                #endregion
                _Redis.SetHashMemory(key, data);
            }
            else
            {

                await _BusShoppingCartDto.Pulish(inputDto);
                var cacheData = _Mapper.Map<ShoppingCartCto>(inputDto);
                _Redis.SetHashMemory(key, cacheData);

            }
            await _Redis.SetRedisZSetAsync(idxKey, key);
        }
    }
}